package com.jjty.dataGenerator.utils;

import cn.hutool.core.util.StrUtil;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class EncryptUtils {
    private static final Logger log = LoggerFactory.getLogger(EncryptUtils.class);
    private static final String PADDING = "AES/CBC/PKCS5Padding"; // 假设使用CBC模式和PKCS5Padding


    //加密
    public static String AESEncode(String content, String AES_KEY, String VIPARA) {
        if (StrUtil.isBlank(content)) {
            return content;
        }
        String AES_encode = "";
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(AES_KEY.getBytes("utf-8"), "AES");
            Cipher cipher = Cipher.getInstance(PADDING);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(VIPARA.getBytes("utf-8")));
            byte[] byte_encode = content.getBytes("utf-8");
            byte[] byte_AES = cipher.doFinal(byte_encode);
            AES_encode = Base64.encodeBase64String(byte_AES);
        } catch (Exception e) {
            log.error("加密过程错误：", e);
        }
        return AES_encode;
    }

    //解密
    public static String AESDecode(String encryptedContent, String AES_KEY, String VIPARA) {
        if (encryptedContent == null || encryptedContent.isEmpty()) {
            return encryptedContent;
        }
        try {
            SecretKeySpec keySpec = new SecretKeySpec(AES_KEY.getBytes("UTF-8"), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(VIPARA.getBytes("UTF-8")));
            byte[] decryptedBytes = cipher.doFinal(Base64.decodeBase64(encryptedContent));
            return new String(decryptedBytes, "UTF-8");
        } catch (Exception e) {
            log.error("解密失败", e);
            throw new RuntimeException("解密失败", e);
        }
    }
}